<template>
  <div>
    <Light v-for="(lightOption,index) of lightOptions"
           :lightOption="lightOption"
           :status="lightStatus[index]"
           :key="index"
    />
    <div>计时器:{{ time }}</div>
    <div>option: {{ lightOptions }}</div>
  </div>
</template>

<script>
import Light from '@/components/Light'

export default {
  name: "LightControl",
  data: function () {
    return {
      lightOptions: [
        {color: "#FF0000", duration: 6000, twinkleDuration: 2000,},
        {color: "#00FF00", duration: 5000, twinkleDuration: 3000,},
        {color: "#FFFF00", duration: 6000},
      ],
      lightStatus: [0, 0, 0],
      time: 0,
    }
  },
  components: {
    Light
  },
  created() {
    this.lightControl(this.lightOptions)
    this.startTimer()
  },
  methods: {
    startTimer() {
      let start = new Date()
      let now = new Date()
      let that = this

      function next() {
        now = new Date()
        that.time = Math.floor((now - start) / 1000)
        setTimeout(next, 1000)
      }

      next()
    },
    changeStatus: function (i, value) {
      this.lightStatus.splice(i, 1, value)
    },
    createLight: function (color, duration, twinkleDuration = 0, i) { // 信号灯
      let brightDuration = duration - twinkleDuration
      let that = this

      function bright() {			// 亮
        return new Promise(function (resolve) {
          that.changeStatus(i, 1)
          setTimeout(resolve, brightDuration);
        })
      }

      function twinkle() {	// 闪烁
        return new Promise(function (resolve) {
          that.changeStatus(i, 2)
          setTimeout(resolve, twinkleDuration);
        })
      }

      function start() {	// 启动信号灯
        return async function () {
          await bright()
          await twinkle()
          that.changeStatus(i, 0)
        }()
      }

      return {
        start
      }
    },
    lightControl: async function (lightOptions) {
      for (let i = 0; i < lightOptions.length; i++) {
        let {color, duration, twinkleDuration} = lightOptions[i]
        await this.createLight(color, duration, twinkleDuration, i).start()
      }
    }
  },
}
</script>

<style scoped>

</style>
